﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;

using Sustainalytics.ClientDW.Entities;
using Sustainalytics.DataLayer.Shared;
using Sustainalytics.Entities.ConnectionStrings;
using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.ReportGenerator.BL;
using Sustainalytics.BusinessResearchProductStates.Entities.ResearchState;
using Sustainalytics.ESG.Entities;
using Sustainalytics.ESGRatings.BusinessLogic.ESGOnlineReport;
using SimpleInjector;

namespace Sustainalytics.Controversies.BusinessLogic
{
    public class CompanyReportGeneration
    {

        private readonly GeneratePdfBulkReader _bulkReader;
        private readonly Guid _companyId;
        private readonly ReportGenerator.BL.ReportGenerator _reportGenerator;
        private readonly IRepositoryCollection<CorporateData> _repositoryCorporate;
        private readonly IRepositoryCollection<ESGProfile> _repositoryEsg;
        private readonly CorporateData corporate;
        public CompanyReportGeneration(Guid company, Container container)
        {
            _companyId = company;
            _repositoryCorporate = new RepositoryCollection<CorporateData>(PlainBlFactory.GetConnectionString(ConnectionStringType.ClientDW));
            _repositoryEsg =
                new RepositoryCollection<ESGProfile>(
                    PlainBlFactory.GetConnectionString(ConnectionStringType.ClientPlatform));
            var defaultProfile = _repositoryEsg.ReadAllWhere(a => a.Name == "Default").FirstOrDefault();
            corporate = _repositoryCorporate.ReadAllWhere(a => a.Id == company).FirstOrDefault();
            _reportGenerator = new ReportGenerator.BL.ReportGenerator();
            var id = new[] { company };
            _bulkReader = new GeneratePdfBulkReader(
                container.GetInstance<IRepositoryCollection<SubPeerGroupKeyEsgIssue>>(),
                container.GetInstance<IRepositoryCollection<Analyst>>(),
                container.GetInstance<IRepositoryCollection<IndicatorTemplate>>(),
                container.GetInstance<IRepositoryCollection<CorporateData>>(),
                container.GetInstance<IRepositoryCollection<FinancialData>>(),
                container.GetInstance<IRepositoryCollection<RPCompanyProfile>>(),
                container.GetInstance<IRepositoryCollection<RPCompanyESGComputationResult>>(),
                container.GetInstance<IHistoricalDataBusinessLogicUnit>(),
                container.GetInstance<IRepositoryCollection<RPIndicatorExtended>>(),
                container.GetInstance<IRepositoryCollection<RPControversyIndicator>>(),
                container.GetInstance<IRepositoryCollection<ComparisonGroupControversy>>(),
                container.GetInstance<IRepositoryCollection<EventIndicator>>(),
                container.GetInstance<IRepositoryCollection<Incident>>(),
                container.GetInstance<IRepositoryCollection<CompanyKeyESGIssue>>(),
                container.GetInstance<IRepositoryCollection<Source>>(),
                1, id,
                PlainBlFactory.GetConnectionString(ConnectionStringType.ClientDW),
                 defaultProfile,
                s => Debug.WriteLine(s), CancellationToken.None, id);
            _bulkReader.OneTimeDataRead();
        }

        public RenderResult GenerateReport(bool isControversyReport = false)
        {
            if (corporate == null)
                throw new Exception(string.Format("Company:{0} not found in corporate data", _companyId));

            if (corporate.ControversyResearchState.ResearchState != ResearchState.ResearchAvailable && corporate.ComprehensiveEsgResearchState.ResearchState != ResearchState.ResearchAvailable)
                throw new Exception("No research flag valid");

            var reportOfline = isControversyReport
                ? _bulkReader.NextControversyOnlyBulk().ToArray()
                : _bulkReader.NextESGRatingsBulk().ToArray();

            if (!reportOfline.Any())
            {
                throw new Exception(string.Format("No report data offline found for company:{0}", _companyId));
            }

            var result = _reportGenerator.GenerateReportPdf(reportOfline[0], true);

            return result[0];

        }
    }
}
